<template>
  <div class="page-table">
    <div class="page-filter">
      <div class="query">
        <el-form size="mini">
          <ad-datetime-range v-model="searchQuery" @select="search" @search="search"/>
        </el-form>
      </div>
      <div class="op">
        <el-button size="mini" type="primary" plain v-permission="['admin','order:export']" :loading="orderDownloading" @click="exportOrderExcel">导出</el-button>
        <el-button size="mini" type="primary" plain :disabled="cannotEdit" @click="generateContract('transport')">{{transportContractStatus}}</el-button>
        <el-button size="mini" type="primary" plain :disabled="cannotEdit" @click="generateContractS('car')">{{carContractStatus}}</el-button>
<!--        <el-button size="mini" type="primary" plain :disabled="cannotEdit" @click="generateContract('car')" v-if="$store.state.env.company.name == 'anda'">{{carContractStatus}}</el-button>-->
        <el-button size="mini" type="primary" plain @click="orderAdd('/orderAdd')">创建订单</el-button>
        <el-button size="mini" type="primary" plain :disabled="cannotCancel" @click="orderCancel">取消订单</el-button>
        <el-button size="mini" type="primary" plain :disabled="cannotEdit" @click="orderEdit({path: '/order/add', query: {mode: 'edit', ids: orderSelectedRowIds}})">修改</el-button>
      </div>
    </div>
    <ad-table ref="order" class="multi-select"
      :data="orderList" :show-summary="orderSummary" v-loading="orderInitLoading" border u-table :data-changes-scroll-top="orderIsScrollTop"
      @row-click="orderSelectRow" @selection-change="orderSelectRows"
      :searchQuery="orderSearchQuery" @search="orderGetInitList"
      @sort-change="orderSortInitList" @filter-change="orderFilterInitList"
      @table-body-scroll="orderGetMoreList" :height="tableHeight">
<!--      v-el-table-infinite-scroll="orderGetMoreList" :infinite-scroll-distance="600"-->
<!--      :infinite-scroll-disabled="orderComplete"-->
      <ad-table-column type="selection" ctype="selection" fixed/>
      <ad-table-column label="序号" type="index" ctype="index" fixed/>
      <ad-table-column label="订单编号" prop="orderSubNo" ctype="orderNo" searchable w="4c1f" href="/order/detail" fixed/>
      <ad-table-column label="订单状态" prop="status" dictName="order_status" filterable w="4c1f"/>
      <ad-table-column label="制单人" prop="createUserName" searchable w="4c1f" sortable/>
      <ad-table-column label="制单时间" ctype="datetime" prop="createTime" w="1f" sortable/>
      <ad-table-column label="委托方" prop="companyName" searchable w="3c1f"/>
      <ad-table-column label="联系人" prop="linkmanName" searchable w="3c1f"/>
      <ad-table-column label="联系电话" prop="linkmanPhone" searchable w="4c1f"/>
      <ad-table-column label="出发地" prop="startCode" sortable searchable queryPro="startName" ctype="city"/>
      <ad-table-column label="目的地" prop="destinationCode" sortable searchable queryPro="destinationName" ctype="city"/>
      <ad-table-column label="车辆名称" prop="carName" searchable w="4c1f"/>
      <ad-table-column label="车架号" prop="vin" ctype="vin-2f" searchable w="4c1f"/>
      <ad-table-column label="提车方式" prop="pickType" dictName="pickcar_type" filterable w="4c1f"/>
      <ad-table-column label="送车方式" prop="takeType" dictName="takecar_type" filterable w="4c1f"/>
      <ad-table-column label="运输方式" prop="transportType" dictName="transport_way" filterable w="4c1f"/>
      <ad-table-column label="应收运费合计" prop="totalFee" sortable w="6c1f"/>
      <ad-table-column label="运输费" prop="transportFee" sortable w="3c1f"/>
      <ad-table-column label="提车费" prop="pickFee" sortable w="3c1f"/>
      <ad-table-column label="送车费" prop="takeFee" sortable w="3c1f"/>
      <ad-table-column label="客户返款" prop="kickbackFee" sortable w="4c1f"/>
      <ad-table-column label="保险费" prop="insuranceFee" sortable w="3c1f"/>
      <ad-table-column label="开票税额" prop="invoiceFee" sortable w="4c1f"/>
      <ad-table-column label="付款方式" prop="paymentType" dictName="payment_type" filterable width="120">
        <template v-slot="{row}">{{parseStatus(dict, 'payment_type', row.paymentType)}}<span v-if="row.collectionStatus == 2" class="icon-settlement-done">已结算</span></template>
      </ad-table-column>
      <ad-table-column label="订单备注" prop="remark" ctype="remark"/>
    </ad-table>

<!--    <el-dialog title="订单" :visible.sync="orderAdder.visible" custom-class="ad-dialog" width="1000px">-->
<!--      <adder :mode="orderAdder.mode" :id="orderSelectedRowId" :visible.sync="orderAdder.visible"/>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import Value from '@/components/AdValue'
import AdDatetimeRange from '@/components/AdDateTimeRange'
import AdTable from '@/components/AdTable'
import AdTableColumn from '@/components/AdTable/AdTableColumn'
import adder from './add'
import dateRange from '@/utils/dateRange'
import adTable from '@/mixins/adTable/index'
import { getList as orderApiGetList, cancel } from '@/api/order/all'
import transportContract from '@/api/contract/insurance/transport'
import carContract from '@/api/contract/insurance/car'
import {download} from "@/api/data";
import {downloadFile} from "@/utils";
import { parseStatus } from '@/utils/code'

export default {
  name: 'order-all',
  components: { Value, AdDatetimeRange, AdTable, AdTableColumn, adder },
  dicts: ['order_status','payment_type','pickcar_type','takecar_type','transport_way'],
  mixins: [adTable([{name: 'order'}])],
  data() {
    return {
      parseStatus,
      searchQuery: {
        beginSearchTime: dateRange.getCurrentDay()[0].getTime(),
        endSearchTime: dateRange.getCurrentDay()[1].getTime()
      },
      orderDownloading: false,
      tableHeight: document.documentElement.clientHeight - 136,
    }
  },
  created() {
    this.orderGetInitList()
  },
  computed: {
    cannotEdit() {
      const diff = this.orderSelectedRows.map(row => row.updateVersion)
      const canceledOrders = this.orderSelectedRows.filter(row => row.status == -1)
      const cannotEdit = [...new Set(diff)].length != 1 || canceledOrders.length > 0
      return cannotEdit
    },
    cannotCancel() {
      const canceledOrders = this.orderSelectedRows.filter(row => row.status == -1)
      const cannotCancel = this.orderSelectedRows == 0 || canceledOrders.length > 0
      return cannotCancel
    },
    carContractStatus() {
      if (this.orderSelectedRow && this.orderSelectedRow.orderInsurance) {
        if (this.orderSelectedRow.orderContract.canRedo == 1) {
          return '生成保单'
          // return '重新生成保单'
        } else {
          return '查看保单'
        }
      } else {
        return '生成保单'
      }
    },
    transportContractStatus() {
      if (this.orderSelectedRow && this.orderSelectedRow.orderContract) {
        if (this.orderSelectedRow.orderContract.canRedo == 1) {
          return '生成合同'
          // return '重新生成合同'
        } else {
          return '查看合同'
        }
      } else {
        return '生成合同'
      }
    }
  },
  methods: { orderApiGetList,
    search(times) {
      this.searchQuery.beginSearchTime = times.beginSearchTime
      this.searchQuery.endSearchTime = times.endSearchTime
      this.orderGetInitList()
    },
    async orderCancel() {
      await this.$confirm('确定要取消订单吗？','取消订单')
      await cancel(this.orderSelectedRowIds)
      this.orderGetInitList()
    },
    generateContract(style) {
      this.$confirm('确定要生成合同吗？','生成合同').then(() => {
        let contract
        if (style == 'car') {
          if (this.carContractStatus == '查看保单') {
            window.open(this.orderSelectedRow.orderInsurance.path)
            return
          } else {
            contract = carContract
          }
        } else if (style == 'transport') {
          if (this.transportContractStatus == '查看合同') {
            window.open(this.orderSelectedRow.orderContract.path)
            return
          } else {
            contract = transportContract
          }
        } else {
          return
        }

        const loadingStyle = {
          lock: true,
          text: '正在生成合同，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        }
        let loading = this.$loading(loadingStyle)
        const cb = res => {
          if (res.code == 0) {
            loading.close()
            // this.$alert('合同已生成完毕')
            this.$confirm('生成已完成，是否查看', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            }).then(() => {
              window.open(res.data)
            }).finally(() => {
              this.orderGetInitList()
            })
          } else {
            loading.close()
            this.$alert('合同生成失败')
          }
        }
        contract.add(this.orderSelectedRowIds).then(cb)
      })
    },
    generateContractS(style) {
      this.$confirm('确定要生成保单吗？','生成保单').then(() => {
        let contract
        if (style == 'car') {
          if (this.carContractStatus == '查看保单') {
            window.open(this.orderSelectedRow.orderInsurance.path)
            return
          } else {
            contract = carContract
          }
        } else if (style == 'transport') {
          if (this.transportContractStatus == '查看合同') {
            window.open(this.orderSelectedRow.orderContract.path)
            return
          } else {
            contract = transportContract
          }
        } else {
          return
        }

        const loadingStyle = {
          lock: true,
          text: '正在生成保单，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        }
        let loading = this.$loading(loadingStyle)
        const cb = res => {
          if (res.code == 0) {
            loading.close()
            // this.$alert('合同已生成完毕')
            this.$confirm('生成已完成，是否查看', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            }).then(() => {
              window.open(res.data)
            }).finally(() => {
              this.orderGetInitList()
            })
          } else {
            loading.close()
            this.$alert('保单生成失败')
          }
        }
        contract.add(this.orderSelectedRowIds).then(cb)
      })
    },
    exportOrderExcel() {
      this.orderDownloading = true
      const loading = this.$loading({lock: true, text: '正在下载，请稍等...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'})
      download('/api/v2/order/export', {...this.searchQuery}).then(result => {
        downloadFile(result.data, result.headers.downloadFileName, 'xlsx')
        loading.close()
      }).finally(() => {
        loading.close()
        this.orderDownloading = false
      })
    },
  }
}
</script>
